package com.youxin.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.base.TPage;
import com.youxin.task.entity.req.JobSearch;
import com.youxin.task.mapper.JobLogMapper;
import com.youxin.task.model.JobLog;
import com.youxin.task.service.JobLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * description: JobLogServiceImpl <br>
 * date: 2020/3/6 16:21 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class JobLogServiceImpl extends ServiceImpl<JobLogMapper, JobLog> implements JobLogService {
    @Override
    public TPage<JobLog> findJobLogs(JobSearch jobLogSearch) {
        try {
            LambdaQueryWrapper<JobLog> queryWrapper = new LambdaQueryWrapper<>();

            if (StringUtils.isNotBlank(jobLogSearch.getBeanName())) {
                queryWrapper.eq(JobLog::getBeanName, jobLogSearch.getBeanName());
            }
            if (StringUtils.isNotBlank(jobLogSearch.getMethodName())) {
                queryWrapper.eq(JobLog::getMethodName, jobLogSearch.getMethodName());
            }
            if (StringUtils.isNotBlank(jobLogSearch.getParams())) {
                queryWrapper.like(JobLog::getParams, jobLogSearch.getParams());
            }
            if (StringUtils.isNotBlank(jobLogSearch.getStatus())) {
                queryWrapper.eq(JobLog::getStatus, jobLogSearch.getStatus());
            }
            if (StringUtils.isNotBlank(jobLogSearch.getStartTime()) && StringUtils.isNotBlank(jobLogSearch.getEndTime())) {
                queryWrapper
                        .ge(JobLog::getCreateTime, jobLogSearch.getStartTime())
                        .le(JobLog::getCreateTime, jobLogSearch.getEndTime());
            }
            queryWrapper.orderByDesc(JobLog::getCreateTime);
            IPage<JobLog> page =  this.page(new Page<>(jobLogSearch.getCurrentPage(), jobLogSearch.getShowCount()), queryWrapper);
            return TPage.page(page.getRecords(),page.getTotal());
        } catch (Exception e) {
            log.error("获取调度日志信息失败", e);
            return null;
        }
    }

    @Override
    public void saveJobLog(JobLog log) {

            save(log);
    }

    @Override
    public void deleteJobLogs(String[] jobLogIds) {
        List<String> list = Arrays.asList(jobLogIds);
        this.baseMapper.deleteBatchIds(list);
    }
}
